﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mesoBoard.Services;
using mesoBoard.Data;
using Ninject;
using mesoBoard.Data.Repositories;
using mesoBoard.Common;

namespace mesoBoard.Web
{
    public class mbAuthorizeAttribute : AuthorizeAttribute
    {
        private Roles RoleService;
        private SpecialPermissions[] _permission;

        public mbAuthorizeAttribute(params SpecialPermissions[] permissions)
        {
            mbEntities db = new mbEntities();
            this.RoleService = new Roles(new RepositoriesWrapper(db));
            this._permission = permissions;
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.User.Identity.IsAuthenticated)
                return false;

            if (RoleService.UserHasSpecialPermissions(int.Parse(httpContext.User.Identity.Name), SpecialPermissions.Administrator))
                return true;

            bool hasPermission = false;

            foreach (SpecialPermissions permission in this._permission)
            {
                if (RoleService.UserHasSpecialPermissions(int.Parse(httpContext.User.Identity.Name), permission))
                    hasPermission = true;
            }

            return hasPermission;
                       
        }
    }
}